define (require, exports, module) ->
  require 'mods/info/info_css.css'

  infoApi = require 'mods/info/info_api'
  # 引入风险信息字典
  riskInfo = require 'js/risk_dict.json'

  module.exports = Vue.extend

    # 组件模板
    template: require 'mods/info/info_tpl.js'

    # 定义变量
    data: () ->
      # 是否加载完成
      loadedSucc: false
      # 加载失败提示语
      loadedFail: ''
      # 个人用户信息数组
      userInfo: {}
      # 修改用户信息弹窗是否显示
      dialogState: false
      # 修改信息
      alterType: ''
      # 用户选择的证件类型和证件类型名称
      id_obj: {}
      # 修改用户信息提交参数
      alterOpt: {}
      # 错误信息
      errMsg: ''
      # 加密前的证件号码
      id_no: ''
      # 证件类型
      idCardType: [
        {
          'id_kind': '0',
          'id_kind_name': '身份证'
        }, {
          'id_kind': '1',
          'id_kind_name': '外国护照'
        }, {
          'id_kind': 'S',
          'id_kind_name': '港澳台居民身份证'
        }, {
          'id_kind': 'G',
          'id_kind_name': '港澳居民来往内地通行证'
        }, {
          'id_kind': 'H',
          'id_kind_name': '台湾居民来往大陆通行证'
        }
      ]
      # 身份证地区
      aCity:
        11: '北京'
        12: '天津'
        13: '河北'
        14: '山西'
        15: '内蒙古'
        21: '辽宁'
        22: '吉林'
        23: '黑龙江'
        31: '上海'
        32: '江苏'
        33: '浙江'
        34: '安徽'
        35: '福建'
        36: '江西'
        37: '山东'
        41: '河南'
        42: '湖北'
        43: '湖南'
        44: '广东'
        45: '广西'
        46: '海南'
        50: '重庆'
        51: '四川'
        52: '贵州'
        53: '云南'
        54: '西藏'
        61: '陕西'
        62: '甘肃'
        63: '青海'
        64: '宁夏'
        65: '新疆'
        71: '台湾'
        81: '香港'
        82: '澳门'
        91: '国外'

    # 定义方法
    methods:

      # 插件加载
      pluginLoad: () ->
        self = @

      # 加载成功
      loadedSuccFunc: () ->
        self = @
        self.$nextTick () ->
          # 加载成功标识
          self.loadedSucc = true
          # 插件加载
          self.pluginLoad()

      # 风险测评
      doRiskExam: () ->
        self = @
        self.$router.push {path: '/risk'}

      # 从session中获取用户信息
      getUserInfo: () ->
        self = @
        # 从session中获取用户信息
        user_info_str = sessionStorage.getItem 'userInfo'
        self.userInfo = JSON.parse user_info_str

        # 修改表单中默认的证件类型
        self.id_obj['id_kind'] = self.userInfo.id_kind
        self.id_obj['id_kind_name'] = self.userInfo.id_kind_name

        # 将用户信息复制到修改对象中
        _.forIn self.userInfo, (value, key) ->
          self.alterOpt[key] = value

        # 证件号加密显示
        self.id_no = self.userInfo.id_no
        id_len = self.id_no?.length
        self.userInfo.id_no = self.id_no.substr(0,3) + "******" + self.id_no.substr(id_len-3)

        # 加载成功 - 处理函数
        self.loadedSuccFunc()

      # 点击修改，弹出修改信息弹窗
      onAlterInfoFun: (type) ->
        self = @
        self.errMsg = ''
        self.alterType = type
        self.dialogState = true

      # 点击弹窗修改按钮，提交修改信息
      onSubmitAlterInfo: () ->
        self = @

        # 保存更改字段以便判断某个字段的唯一性
        self.alterOpt['alter_type'] = self.alterType

        if 'id_info' is self.alterType

          if self.id_obj.id_kind is self.userInfo.id_kind and self.alterOpt.id_no is self.id_no
            self.dialogState = false
            return

          flag = self.isCardID self.alterOpt.id_no

          if '0' is self.id_obj.id_kind and true isnt flag
            self.errMsg = flag
            return

          self.id_no = self.alterOpt.id_no
          self.alterOpt.id_kind = self.id_obj.id_kind
          self.alterOpt.id_kind_name = self.id_obj.id_kind_name

          self.updateUserInfo()

        else
          # 将加密前的证件号码设置回去
          self.alterOpt.id_no = self.id_no

          if self.alterOpt[self.alterType] is self.userInfo[self.alterType]
            self.dialogState = false
            return

          self.updateUserInfo()

      # 提交修改信息
      updateUserInfo: () ->
        self = @

        params =
          user: self.alterOpt

        return infoApi.updateUserInfo params
          .then (res) ->
            # 修改成功，处理session数据
            self.dealAlterSucc res

          .catch (err) ->
            self.errMsg = err?.data?.error or '异常错误'
            console.error '修改个人信息出错:',err

      # 获取用户风险等级信息
      getUserRiskInfo: () ->
        self = @

        params =
          "id_no": self.alterOpt.id_no
          "id_kind": self.alterOpt.id_kind
          "dsorgan_flag": '0'

        return infoApi.getUserRiskInfo params
          .then (res) ->
            if 200 isnt res?.status
              console.log 'errCode:', res?.status
            else
              # 返回信息
              resData = res?.data?.table_data
              # 为空，则没有做过风险测评，默认为0
              if 0 is resData?.length
                risk_level = 0
              # 不为空，则匹配相应信息
              else
                risk_level = resData[0]?.corp_risk_level
                tzpz = resData[0]?.client_invest_type
                tzqx = resData[0]?.client_term_type

              # 用户适当性三要素添加到sessionStorage
              self.userInfo.risk_level_name = riskInfo[0][risk_level]?.risk_level_name
              self.userInfo.risk_level = risk_level
              self.userInfo.tzpz_name = riskInfo[2][tzpz-1]?.tzpz_name
              self.userInfo.tzpz = tzpz
              self.userInfo.tzqx_name = riskInfo[1][tzqx-1]?.tzqx_name
              self.userInfo.tzqx = tzqx

      # 修改成功后的处理
      dealAlterSucc: (res) ->
        self = @

        # 如果修改了证件信息，则重新获取用户三要素
        if self.alterOpt.id_no isnt self.userInfo.id_no or self.alterOpt?.id_kind isnt self.userInfo.id_kind

          # 从交易柜台接口获取用户三要素
          self.getUserRiskInfo()

            .then (resRisk) ->

              # 给用户信息设置修改成功的值
              if 'id_info' is self.alterType
                self.userInfo.id_no = self.alterOpt?.id_no
                self.userInfo.id_kind = self.alterOpt?.id_kind
                self.userInfo.id_kind_name = self.alterOpt?.id_kind_name

              else
                self.userInfo[self.alterType] = self.alterOpt[self.alterType]

              # 将修改后的用户信息存在session中
              oStr = JSON.stringify self.userInfo
              sessionStorage.setItem 'userInfo', oStr

              # 证件号加密显示
              tmpIdNo = self.userInfo.id_no
              id_len = tmpIdNo?.length
              self.userInfo.id_no = tmpIdNo.substr(0,3) + "******" + tmpIdNo.substr(id_len-3)

              # 隐藏修改弹窗
              self.dialogState = false

            .catch (errRisk) ->
              self.errMsg = errRisk?.data?.error
              console.log 'err:', errRisk

          return

        # 给用户信息设置修改成功的值
        if 'id_info' is self.alterType
          self.userInfo.id_no = self.alterOpt?.id_no
          self.userInfo.id_kind = self.alterOpt?.id_kind
          self.userInfo.id_kind_name = self.alterOpt?.id_kind_name
        else
          self.userInfo[self.alterType] = self.alterOpt[self.alterType]

        # 将修改后的用户信息存在session中
        oStr = JSON.stringify self.userInfo
        sessionStorage.setItem 'userInfo', oStr

        # 隐藏修改弹窗
        self.dialogState = false

      # 验证身份证的合法性
      isCardID : (sId) ->
        self = @
        iSum = 0
        info = ''
        if !/^\d{17}(\d|x)$/i.test(sId)
          return '你输入的身份证长度或格式错误'
        sId = sId.replace(/x$/i, 'a')
        if self.aCity[parseInt(sId.substr(0, 2))] == null
          return '你的身份证地区非法'
        sBirthday = sId.substr(6, 4) + '-' + Number(sId.substr(10, 2)) + '-' + Number(sId.substr(12, 2))
        d = new Date(sBirthday.replace(/-/g, '/'))
        if sBirthday != d.getFullYear() + '-' + (d.getMonth() + 1) + '-' + d.getDate()
          return '身份证上的出生日期非法'
        i = 17
        while i >= 0
          iSum += 2 ** i % 11 * parseInt(sId.charAt(17 - i), 11)
          i--
        if iSum % 11 != 1
          return '你输入的身份证号非法'
        true

    # 引用组件
    components:
      'c-info-side': require 'mods/info_side/info_side_mod'

    # 计算属性
    computed:

      # 加载中的样式
      loaddingClass: () ->
        self = @
        if self.loadedSucc
          return 'c-hidden'
        if self.loadedFail
          return 'c-hidden'
        return ''

      # 加载成功的样式
      loadedSuccClass: () ->
        self = @
        return if self.loadedSucc then '' else 'c-vhidden'

      # 加载失败的样式
      loadedFailClass: () ->
        self = @
        return if self.loadedFail then '' else 'c-hidden'

    # 组件初始化执行
    mounted: () ->
      self = @
      # 从session中获取用户信息
      self.getUserInfo()